io = require("io")
require("vlc")

function descriptor()
    return {
        title = "Print Frame Time",
        version = "1.0",
        author = "Your Name",
        capabilities = {"playing-listener"}
    }
end

local file_my = {
  mp4name = "",
  filename = "",
}


function playing_changed()

    if vlc.playlist.status() == "paused" then
		local timestamp = vlc.var.get(vlc.object.input(), "time")
		
        vlc.msg.info("Current frame time: " .. timestamp)

		--io.write(timestamp .. "\n")
		write_to_file(timestamp)
		
    end
end

function write_to_file(content)
    -- 打开文件并将内容写入文件
    local file = io.open(file_my.filename, "a")
    file:write(file_my.mp4name.." "..content .. "\n")
    file:close()
end

local function url_decode(str)
    str = string.gsub(str, "+", " ")
    str = string.gsub(str, "%%(%x%x)", function(h)
        return string.char(tonumber(h, 16))
    end)
    return str
end

function activate()
	local media = vlc.input.item()
	
	if not media then
	  print("没有正在播放的媒体文件")
	  return
	end
	local fullpath = media:uri()
	local mp4name = string.match(fullpath, ".+/([^/]+)$")
	decoded_mp4name = url_decode(mp4name)
	vlc.msg.info(decoded_mp4name)
	file_my.mp4name = decoded_mp4name

	local timestamp = os.time()
	time_str = os.date("%Y%m%d_%H%M%S", timestamp)
	path = "lua/extensions//output_"
	file_my.filename = path ..time_str .. ".txt"

	vlc.msg.info("Hello, build "..file_my.filename)

	
    local filename = os.date(file_my.filename)
	local file = io.open(file_my.filename, "a")
	io.output(file)
	--write_to_file(decoded_mp4name)
	-- 关闭文件句柄
	--io.close(file)
end

function deactivate()
    vlc.msg.info("Goodbye")
end
